package com.qwen.service.impl;

import com.alibaba.cloud.ai.tongyi.audio.api.SpeechClient;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisAudioFormat;
import com.qwen.service.TongyiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.image.ImageClient;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @program: springboot3-demos
 * @description:
 * @author: Reagan Li
 * @create: 2024-07-03 16:02
 **/

@Slf4j
@Service
public class TongyiServiceImpl implements TongyiService {

    @Autowired
    private ChatClient chatClient;

    @Autowired
    private ImageClient imageClient;

    @Autowired
    private SpeechClient speechClient;

    @Override
    public String chat(String msg) {
        String call = chatClient.call(msg);
        return call;
    }

    @Override
    public ImageResponse genImg(String imgPrompt) {
        var prompt = new ImagePrompt(imgPrompt);
        return imageClient.call(prompt);
    }

    @Override
    public String genAudio(String text) {
        log.info("gen audio prompt is: {}", text);
        var resWAV = speechClient.call(text);
        // save的代码省略，就是将音频保存到本地而已
        return save(resWAV.array(), SpeechSynthesisAudioFormat.WAV.getValue());
    }

    private static final String SAVE_DIRECTORY = "/Users/6clk-new/springai/";

    private String save(byte[] audioData, String audioFormat) {
        String fileName = generateFileName(audioFormat);
        Path filePath = Paths.get(SAVE_DIRECTORY, fileName);

        try {
            Files.write(filePath, audioData);
            return filePath.toString();
        } catch (IOException e) {
            log.error("Failed to save audio file: {}", e.getMessage());
            return null; // 或者抛出异常，视情况而定
        }
    }

    private String generateFileName(String audioFormat) {
        return "audio_" + System.currentTimeMillis() + "." + audioFormat.toLowerCase();
    }
}
